package learn_concurrent._11;

import java.util.concurrent.atomic.AtomicMarkableReference;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AtomicMarkableReferenceTest {
	static Logger logger = LoggerFactory.getLogger(AtomicMarkableReferenceTest.class);
	
	public static void main(String[] args) throws InterruptedException {
		GarbageBag bag = new GarbageBag("full");
		AtomicMarkableReference<GarbageBag> ref = 
				new AtomicMarkableReference<>(bag, true);
		
		GarbageBag prev = ref.getReference();
		logger.info(prev.toString());
		
		// cleaner thread
		new Thread(() -> {
			bag.setValue("empty");
			ref.compareAndSet(bag, bag, true, false);
			logger.info(bag.toString());
		}, "cleaner-thread").start();
		// cleaner thread
		
		Thread.sleep(1000);
		
		logger.info("Want to change a new garbage bag?");
		
		boolean success = ref.compareAndSet(prev, new GarbageBag("empty"), true, false);
		
		logger.info("success : {}", success);
		
		logger.info(ref.getReference().toString());
		
	}
	
}

class GarbageBag {
	
	private String value;

	public GarbageBag(String value) {
		this.value = value;
	}
	
	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	@Override
	public String toString() {
		return super.toString() + "  " + value;
	}
	
}
